package com.technician.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.technician.common.DeleteRequest;
import com.technician.common.ResponseResult;
import com.technician.exceptionHandler.GlobalSystemException;
import com.technician.model.dto.goodsType.GoodsTypeInsertRequest;
import com.technician.model.dto.goodsType.GoodsTypeQueryRequest;
import com.technician.model.dto.goodsType.GoodsTypeUpdateRequest;
import com.technician.model.entity.GoodsType;
import com.technician.model.entity.User;
import com.technician.model.enums.HttpStatusEnum;
import com.technician.model.security.LoginUser;
import com.technician.model.vo.GoodsTypeVO;
import com.technician.service.GoodsTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/goodsType")
public class GoodsTypeController {

    @Autowired
    private GoodsTypeService goodsTypeService;

    /**
     * 新增一个商品分类（管理员）
     *
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult save(@RequestBody @Validated GoodsTypeInsertRequest goodsTypeInsertRequest){

        // 获取登录用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = loginUser.getUser();

        GoodsType goodsType = new GoodsType();
        // 拷贝 分类名称和描述
        BeanUtils.copyProperties(goodsTypeInsertRequest,goodsType);
        goodsType.setStatus("0");
        goodsType.setCreateBy(user.getId());
        goodsType.setCreateTime(LocalDateTime.now());
        goodsType.setUpdateBy(user.getId());
        goodsType.setUpdateTime(LocalDateTime.now());

        // 插入
        boolean save = goodsTypeService.save(goodsType);
        if (!save){
            throw new GlobalSystemException(400,"插入失败");
        }

        return ResponseResult.success("新建商品分类成功");
    }

    /**
     * 删除一个商品分类 （管理员）
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult<Boolean> deleteGoodsTypeById(@RequestBody @Validated DeleteRequest deleteRequest) {
        //todo 删除分类下的商品
        boolean b = goodsTypeService.removeById(deleteRequest.getId());
        if (!b){
            return ResponseResult.error(400,"删除失败");
        }
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE);
    }


    /**
     * 修改一个商品分类 （管理员）
     *
     * @param updateRequest
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult<Boolean> updateGoodsTypeById(@RequestBody @Validated GoodsTypeUpdateRequest updateRequest) {
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long id = loginUser.getUser().getId();

        GoodsType goodsType = new GoodsType();
        BeanUtils.copyProperties(updateRequest,goodsType);
        goodsType.setUpdateBy(id);
        goodsType.setUpdateTime(LocalDateTime.now());

        boolean b = goodsTypeService.updateById(goodsType);
        if (!b){
            return ResponseResult.error(400,"修改失败");
        }
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE);
    }

    /**
     * 查询商品分类列表 （管理员）
     *
     * @param goodsTypeQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult<Page<GoodsType>> listGoodsTypeByPage(@RequestBody GoodsTypeQueryRequest goodsTypeQueryRequest) {
        long current = goodsTypeQueryRequest.getCurrent();
        long size = goodsTypeQueryRequest.getPageSize();
        Page<GoodsType> goodsTypePage = goodsTypeService.page(new Page<>(current, size),
                goodsTypeService.getQueryWrapper(goodsTypeQueryRequest));
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE, goodsTypePage);
    }

    /**
     * 查询商品分类列表
     *
     * @param goodsTypeQueryRequest
     * @return
     */
    @PostMapping("/listVO/page")
    public ResponseResult<Page<GoodsTypeVO>> listGoodsTypeVOByPage(@RequestBody GoodsTypeQueryRequest goodsTypeQueryRequest) {
        ResponseResult<Page<GoodsType>> pageResponseResult = listGoodsTypeByPage(goodsTypeQueryRequest);
        Page<GoodsType> data = pageResponseResult.getData();
        List<GoodsType> records = data.getRecords();
        List<GoodsTypeVO> collect = records.stream().map(GoodsTypeVO::objToVo).collect(Collectors.toList());

        long current = goodsTypeQueryRequest.getCurrent();
        long size = goodsTypeQueryRequest.getPageSize();
        Page<GoodsTypeVO> goodsTypeVOPage = new Page<>();
        goodsTypeVOPage.setCurrent(current);
        goodsTypeVOPage.setSize(size);
        goodsTypeVOPage.setRecords(collect);
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE, goodsTypeVOPage);
    }

    /**
     * 根据 id 获取 商品分类 （管理员）
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult<GoodsType> getUserById(@RequestParam Long id) {
        if (id < 0) {
            throw new GlobalSystemException(400,"请求参数异常");
        }
        GoodsType goodsType = goodsTypeService.getById(id);
        if (goodsType == null) {
            throw new GlobalSystemException(400,"账号不存在");
        }
        return ResponseResult.success(goodsType);
    }
}
